<template>
  <u-form-item
    :label="label"
    :prop="props.data.field"
    :required="props.data.required"
  >
    <u-input
      v-model="val"
			inputAlign="right"
			:type="props.data.precision ? 'digit' : 'number'"
      :placeholder="props.data.placeholder"
      :readonly="props.data.readonly"
      :disabled="props.data.disabled"
			@blur="onBlur"
      @change="onChange"
    />
  </u-form-item>
</template>

<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { useProps } from '../hooks/props'
import { isNumber } from '../../../utils/util'

const props = defineProps<{ data: Record<string, any>; form: Record<string, any> }>()
const emits = defineEmits(['valueChange'])

const { label } = useProps(props)
const val = ref()
const last = ref()

const onChange = (value: any) => {
	if (isNumber(value)) {
		emits('valueChange', { name: props.data.field, value: val.value })
		last.value = val.value
	} else {
		nextTick(() => {
			val.value = last.value
			emits('valueChange', { name: props.data.field, value: val.value })
		})
	}
}

const onBlur = () => {
	val.value = props.data.precision ? parseFloat(val.value) : parseInt(val.value)	
	if (props.data.min || props.data.min == 0) {
		if (val.value < props.data.min) {
			nextTick(() => {
				val.value = props.data.min
				last.value = val.value
				emits('valueChange', { name: props.data.field, value: val.value})
			})				
		}
	}
	if (props.data.max || props.data.max == 0) {
		if (val.value > props.data.max) {
			nextTick(() => {
				val.value = props.data.max
				last.value = val.value
				emits('valueChange', { name: props.data.field, value: val.value })
			})
		}
	}
}

watch(
	() => props.data.defaultVal,
	() => {
		val.value = props.data.defaultVal
		if (emits) {
			emits('valueChange', { name: props.data.field, value: val.value })
		}
	},
	{ immediate: true }
)
</script>

<style lang="scss" scoped></style>
